//
//  ChooseTypeController.m
//  QQplayground
//
//  Created by zhangxy on 2018/6/19.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "ChooseTypeController.h"
#import "MyButton.h"

#import "NavTypeEntity.h"
#import "ZZChooseLabelCell.h"
#define cellIdentifier @"ZZChooseLabelCell"

@interface ChooseTypeController (){
    MyButton *checkBtn;
    NSIndexPath *checkPath;
}

@property(nonatomic,strong) NSMutableArray *listArray;
@property(nonatomic,strong) NSMutableArray *navArray;

@property(nonatomic,strong) UITableView *listTable;
@property(nonatomic,strong) UIScrollView *mainScroll;

@end

@implementation ChooseTypeController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [super viewDidLoad];
    self.navigationItem.title = @"选择分类";
    [self setNavigationBar];
    
    self.navigationController.navigationBarHidden = NO;
    
    [self.view setBackgroundColor:UIColorFromRGB(BgSystemColor)];
    [self createTableView];
}



-(void)createTableView{
    _listArray = [[NSMutableArray alloc] init];
    _navArray  = [[NSMutableArray alloc] init];
    
    _mainScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(20, 10, 65, self.view.frame.size.height-20)];
    [_mainScroll setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:_mainScroll];
    
    _mainScroll.showsHorizontalScrollIndicator = NO;
    _mainScroll.showsVerticalScrollIndicator = NO;
    _mainScroll.alwaysBounceHorizontal = NO;
    _mainScroll.alwaysBounceVertical = YES;
    _mainScroll.pagingEnabled = NO;
    //    _mainScroll.bounces = NO;
    _mainScroll.scrollEnabled = YES;
    
    
    
    _listTable=[self.view createTableView:self cell:cellIdentifier];
    [_listTable setFrame:CGRectMake(95, 10, ScreenWidth - 105, self.view.frame.size.height-20)];
    _listTable.layer.cornerRadius = 10.0f;
    _listTable.layer.masksToBounds = YES;
    [_listTable setBackgroundColor:UIColorFromRGB(TextWhiteColor)];
    
    if (iOS7) {
        _listTable.backgroundView = nil;
    }
    UIView *footer =[ [UIView alloc]init];
    footer.backgroundColor = [UIColor clearColor];
    [_listTable setTableFooterView:footer];
    
    
    [_listTable setSeparatorColor:LINE_COLOR];
    [_listTable setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    
    
    [self setTableSeparatorInset];
    
    
    
    [self getChannelListByNetWork];
}


-(void)actionButton:(MyButton *) btn{
    if(checkBtn!=nil){
        checkBtn.selected = NO;
    }
    btn.selected = YES;
    checkBtn = btn;
    
    [self loadBegin];
}

/**
 加载更多
 */
-(void)getChannelListByNetWork{
    
    [NetworkUtil POST:API_GetNavList parameters:@{} success:^(id responseObject, NSDictionary *dict) {
        NSArray *arr = dict[@"data"];
        
        // 设置图片
        NSDictionary *navDict = @{@"avatar":@"选择 头像",
                                  @"pic":@"选择 图片",
                                  @"group":@"选择 分组",
                                  @"skin":@"选择 壁纸",
                                  @"sign":@"选择 签名",
                                  @"show":@"选择 自拍",
                                  @"name":@"选择 网名",
                                  @"default":@"选择 签名"};
        int i=1;
        CGFloat itemW = 65;
        for (NSDictionary *item in arr) {
            NavTypeEntity *model = [[NavTypeEntity alloc] initWithDictionary:item];
            [self.navArray addObject:model];
            
            MyButton *btn = [MyButton buttonWithType:UIButtonTypeCustom];
            [btn setFrame:CGRectMake(0,(i-1)*10 + (i-1)*itemW, itemW, itemW)];
            [btn setTitleColor:DEEP_GRAY_COLOR forState:UIControlStateNormal];
            [btn.titleLabel setFont:ListElevenFont];
            btn.layer.cornerRadius = 15;
            btn.layer.masksToBounds = YES;
            btn.tag = i-1;
            btn.objTag = model;
            [btn setTitleColor:UIColorFromRGB(TextSizeOneColor) forState:0];
            [btn setTitleColor:UIColorFromRGB(BgTitleColor) forState:UIControlStateSelected];
            [btn setTitleEdgeInsets:UIEdgeInsetsMake(36, 0, 13, 0)];
            [btn addTarget:self action:@selector(actionButton:) forControlEvents:UIControlEventTouchUpInside];
            if(convertToString(navDict[model.nav_type]).length > 0){
                [btn setBackgroundImage:[UIImage imageNamed:convertToString(navDict[model.nav_type])] forState:UIControlStateNormal];
                [btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@ copy",convertToString(navDict[model.nav_type])]] forState:UIControlStateSelected];
            }else{
                [btn setBackgroundImage:[UIImage imageNamed:convertToString(navDict[@"default"])] forState:UIControlStateNormal];
                [btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@ copy",convertToString(navDict[@"default"])]] forState:UIControlStateSelected];
            }
            [btn setTitle:convertToString(model.nav_name) forState:UIControlStateNormal];
            [self.mainScroll addSubview:btn];
            if(i == 1){
                btn.selected = YES;
                checkBtn = btn;
            }
            i = i + 1;
        }
        
        [self loadBegin];
    } failure:^(NSError *error, NSString *message) {
        
    }];
}



-(void)loadBegin{
    [_listArray removeAllObjects];
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self loadMoreData];
}


/**
 加载更多
 */
-(void)loadMoreData{
    if(checkBtn==nil){
        return;
    }
    NavTypeEntity *entity = checkBtn.objTag;
    
    [NetworkUtil POST:API_GetCatList parameters:@{@"nav_id":convertToString(entity.nav_id)} success:^(id responseObject, NSDictionary *dict) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSArray *arr = dict[@"data"];
        for (NSDictionary *item in arr) {
            NavTypeEntity *model = [[NavTypeEntity alloc] initWithDictionary:item];
            [self.listArray addObject:model];
        }
        
        [self.listTable setFrame:CGRectMake(95, 10, ScreenWidth - 105, arr.count * 44)];
        [self.listTable reloadData];
    } failure:^(NSError *error, NSString *message) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}



#pragma mark UITableView delegate Start
// 返回section数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

// 返回section高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return  0;
}

// 返回section 的View
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectZero];
    if(section == 0){
        
    }
    return headerView;
}

// 返回section下得行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _listArray.count;
}

// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZZChooseLabelCell *cell = (ZZChooseLabelCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[ZZChooseLabelCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    NavTypeEntity *entity = [_listArray objectAtIndex:indexPath.row];
    if(checkPath!=nil && checkPath.row == indexPath.row){
        [cell dataToView:entity index:YES];
    }else{
        [cell dataToView:entity index:NO];
    }
    
    return cell;
}



// 是否显示删除功能
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

// 删除清理数据
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    editingStyle = UITableViewCellEditingStyleDelete;
}


// table 行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    return 70.0f;
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

// table 行的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NavTypeEntity *entity=[_listArray objectAtIndex:indexPath.row];
    if(_ZZChooseResultBlock){
        if(checkBtn){
            NavTypeEntity *nav = checkBtn.objTag;
            entity.nav_type = nav.nav_type;
            entity.nav_name = nav.nav_name;
        }
        _ZZChooseResultBlock(entity);
    }
    
    [self backAction];
    
}

//设置分割线间距
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row < _listArray.count-1){
        UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:inset];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:inset];
        }
    }else{
        UIEdgeInsets inset = UIEdgeInsetsMake(0, ScreenWidth, 0, 0);
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:inset];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:inset];
        }
    }
}

-(void)viewDidLayoutSubviews{
    [self setTableSeparatorInset];
}
#pragma mark UITableView delegate end

/**
 *  设置UITableView分割线空隙
 */
-(void)setTableSeparatorInset{
    UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
    if ([_listTable respondsToSelector:@selector(setSeparatorInset:)]) {
        [_listTable setSeparatorInset:inset];
    }
    
    if ([_listTable respondsToSelector:@selector(setLayoutMargins:)]) {
        [_listTable setLayoutMargins:inset];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
